package com.xzssmk.leisure.x.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzssmk.leisure.x.mapper.CardInventoryMapper;
import com.xzssmk.leisure.x.mapper.CardTypeMapper;
import com.xzssmk.leisure.x.mapper.CommissionMapper;
import com.xzssmk.leisure.x.mapper.IssuePeriodMapper;
import com.xzssmk.leisure.x.mapper.OrderConsumeMapper;
import com.xzssmk.leisure.x.mapper.PresentReceiveMapper;
import com.xzssmk.leisure.x.po.CardInventory;
import com.xzssmk.leisure.x.po.CardType;
import com.xzssmk.leisure.x.po.Commission;
import com.xzssmk.leisure.x.po.IssuePeriod;
import com.xzssmk.leisure.x.po.OrderConsume;
import com.xzssmk.leisure.x.po.PresentReceive;
import com.xzssmk.leisure.x.po.SysUsr;
import com.xzssmk.leisure.x.service.BaseService;
import com.xzssmk.leisure.x.service.CommissionService;
import com.xzssmk.leisure.x.util.DataTables;
import com.xzssmk.leisure.x.util.OrderUtils;
import com.xzssmk.leisure.x.util.RequestStatusUtil;
import com.xzssmk.leisure.x.util.VerifyCodeUtil;
import com.xzssmk.leisure.x.vo.CommissionViewVo;
import com.xzssmk.leisure.x.vo.CommissionVo;

@Service
public class CommissionServiceImpl extends BaseService implements CommissionService {

    @Autowired
    IssuePeriodMapper issuePeriodMapper;

    @Autowired
    OrderConsumeMapper orderConsumeMapper;

    @Autowired
    CardTypeMapper cardTypeMapper;

    @Autowired
    CardInventoryMapper cardInventoryMapper;

    @Autowired
    CommissionMapper commissionMapper;

    @Autowired
    PresentReceiveMapper presentReceiveMapper;

    @Transactional
    @Override
    public Map<String, Object> add(CommissionVo commissionVo, SysUsr sysUsr) throws Exception {

        Map<String, Object> map = new HashMap<>();
        if (null == sysUsr) {
            map.put("status", RequestStatusUtil.FAILURE);
            return map;
        }
        /**
         * 1.订单表 order_consume 2.card_inventory 卡库 3.commission 分销表
         */
        try {
            // 订单表
            OrderConsume orderConsume = new OrderConsume();
            orderConsume.setOrderNumber(OrderUtils.generateOrderNo("bgxzssmk"));// 订单号
            Short quantity = commissionVo.getQuantity();
            orderConsume.setQuantity(quantity);// 数量
            IssuePeriod issuePeriod = issuePeriodMapper.selectByPrimaryKey(commissionVo.getIssuePeriodId());
            Short salePrice = issuePeriod.getSalePrice();
            Integer totalAmount = quantity * salePrice;
            orderConsume.setAmount(Short.valueOf(String.valueOf(totalAmount)));// 金额
            orderConsume.setPurchaseMethod(new Byte("2"));// 购买方式
            orderConsume.setCreateTime(new Date());
            orderConsume.setModifyTime(new Date());
            orderConsume.setCustomId(sysUsr.getUsrId());
            orderConsume.setIssuePeriodId(commissionVo.getIssuePeriodId());
            orderConsumeMapper.insert(orderConsume);

            // 卡库表
            String typeSymbol = issuePeriod.getCardType();
            CardType byCardType = cardTypeMapper.getTypeSymbol(typeSymbol);
            // 生成卡号
            int cardinalNumber = Integer.parseInt(byCardType.getCardinalNumber());
            String cardNumber = "";
            String newCardinalNumber = "";
            for (int i = 0; i < quantity; i++) {
                cardinalNumber++;
                cardNumber = String.valueOf(cardinalNumber);
                if (cardNumber.length() < 8) {
                    cardNumber = String.format("%08d", Integer.parseInt(cardNumber));
                    newCardinalNumber = cardNumber;
                } else
                    return null;
                cardNumber = cardNumber.replace('4', 'A');
                CardInventory cardInventory = cardInventoryMapper.selectByCardNum(cardNumber);
                if (null != cardInventory)
                    continue;
                cardInventory = new CardInventory();

                // 添加卡库表
                cardInventory.setCardNumber(typeSymbol + cardNumber);// 卡号
                cardInventory.setState(new Byte("2"));
                cardInventory.setOwnType(new Byte("2"));// 购买类型
                cardInventory.setIssuePeriodId(commissionVo.getIssuePeriodId());// 发卡期id
                cardInventory.setOrderId(orderConsume.getOrderId());// 订单id
                cardInventory.setOwnerId(sysUsr.getUsrId());
                cardInventory.setCreateTime(new Date());
                cardInventory.setModifyTime(new Date());
                cardInventoryMapper.insert(cardInventory);

                // 分销表
                Commission commission = new Commission();
                commission.setInventoryId(cardInventory.getInventoryId());// 卡号id
                commission.setCommission(commissionVo.getCommission());// 提成金额/比例
                commission.setCommissionType(commissionVo.getCommissionType());// 提成方式
                commission.setFullName(commissionVo.getFullName());// 姓名
                commission.setPhone(commissionVo.getPhone());// 手机号
                commission.setRecommandCode(VerifyCodeUtil.generateVerifyCode());
                commission.setIssuePeriodId(commissionVo.getIssuePeriodId());
                commission.setCreatTime(new Date());
                commission.setModifyTime(new Date());
                commissionMapper.insert(commission);

                PresentReceive presentReceive = new PresentReceive();
                presentReceive.setInventoryId(cardInventory.getInventoryId());
                presentReceive.setPresenterId(sysUsr.getUsrId());
                presentReceive.setOwnType(new Byte("2"));
                presentReceive.setVerifyCode(VerifyCodeUtil.generateVerifyCode());
                presentReceive.setCreateTime(new Date());
                presentReceive.setModifiyTime(new Date());
                presentReceiveMapper.insertSelective(presentReceive);

            }

            byCardType.setCardinalNumber(newCardinalNumber);

            Integer id = cardTypeMapper.updateByPrimaryKey(byCardType);// 更新卡基数
            if (id > 0) {
                map.put("status", RequestStatusUtil.SUCCESS);
            } else {
                map.put("status", RequestStatusUtil.FAILURE);
            }
            return map;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public DataTables getPageList(DataTables dataTables, String issuePeriodId) {
        PageHelper.startPage(dataTables.getStart(), dataTables.getLength()); // 核心分页代码
        // PageHelper.orderBy("modify_time desc");
        if (!StringUtils.isEmpty(dataTables.getColumn())) {
            String column = propertyToColumn(CommissionMapper.class, dataTables.getColumn());
            if (!StringUtils.isEmpty(column)) {
                PageHelper.orderBy(column + " " + dataTables.getOrder());
            }
        }
        List<CommissionViewVo> list = commissionMapper.getPageList(issuePeriodId, dataTables.getSubSQL());
        PageInfo<CommissionViewVo> pageInfo = new PageInfo<CommissionViewVo>(list);
        dataTables.setRecordsTotal(pageInfo.getTotal());
        dataTables.setRecordsFiltered(pageInfo.getTotal());
        dataTables.setData(pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());

        return dataTables;
    }

    // @Override
    // public Commission getById(Integer id) {
    // return commissionMapper.selectByPrimaryKey(id);
    // }
}
